#include "qdisplaycodeplp.h"
#include "qfilecachedmemory.h"
#include "plpgenerator_define.h"

QDisplayCodePLP::QDisplayCodePLP(QVBoxLayout* layout,QObject*parent)
   : QObject(parent),m_layout(layout)
{
}

QDisplayCodePLP::~QDisplayCodePLP()
{
}


void QDisplayCodePLP::setPartToDisplay(QEXPPart* part)
{
  clearLayout();
  if(part)
  {
    QFileCachedMemory cache;
    QCodePLPGenerator* plp = new QCodePLPGenerator(part,  cache.get(FILE_CACHE_BDD_PLP),
                            cache.get(FILE_CACHE_BDD_MANU),
                            cache.get(FILE_CACHE_BDD_CAT_1),
                            cache.get(FILE_CACHE_BDD_CAT_2),
                            cache.get(FILE_CACHE_BDD_CAT_3),
                            cache.get(FILE_CACHE_BDD_CAT_4),
                            cache.get(FILE_CACHE_BDD_FOURNISSEUR));
    m_layout->addWidget(plp);  
    connect(plp,SIGNAL(modifyPLPValid()),this,SLOT(modify()));
    connect(plp,SIGNAL(addPLPValid()),this,SLOT(add()));
  }
}

void QDisplayCodePLP::clearLayout()
{
  while(m_layout->count())
  {
    QWidget* widget = m_layout->itemAt(0)->widget();
    widget->disconnect();
    m_layout->removeWidget(widget);
    delete (QCodePLPGenerator*) widget;
  }
}

void QDisplayCodePLP::add()
{
  emit addToFile(properties());
}
  
void QDisplayCodePLP::modify()
{
	QStringList p = properties(); 
	if(p.size())
	{
		foreach(QString line,p)
			emit addToFile(line.split(PLPGEN_SEPARATOR));
	 
		emit modifyPart(p.first().split(PLPGEN_SEPARATOR));
	}
}


QStringList QDisplayCodePLP::properties() const
{
  if(m_layout->count())
  {
    QCodePLPGenerator* plp = (QCodePLPGenerator*) m_layout->itemAt(0)->widget();
    return plp->generateLines();
  }
  return QStringList();
}